﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PaperRenderingInterfaces;
using System.ComponentModel.Composition;
using HtmlAgilityPack;
using PaperPluginUtilities;

namespace ATLASConfNotes
{
    /// <summary>
    /// Parse a singel conf note pate
    /// </summary>
    [PaperRender("ATLASConfNotePage")]
    public class ATLASParseConfNotePage : IPaperRender
    {
#pragma warning disable 0649
        [Import]
        private ParseTableForImages tableParser;
#pragma warning restore 0649

#pragma warning disable 0649
        [Import]
        private IWebAccess WebGetter;
#pragma warning restore 0649

        public IEnumerable<DeepZoomPivotConstructor.PivotLib.PivotImage> Render(string renderAddress)
        {
            if (!renderAddress.EndsWith("/"))
            {
                renderAddress += "/";
            }
            var page = new Uri(renderAddress);
            string html = WebGetter.GetUriAsString(page);
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);

            ///
            /// Find the tables that contain the actual text...
            /// 

            var allTables = doc.DocumentNode.SelectNodes("//table");
            tableParser.BaseUri = page;
            var images = new EnumerableWrapper<HtmlNode>(allTables).SelectMany(tableParser.Process);

            ///
            /// Grab the info page and attach that here now
            /// 

            var info = ATLASUtilities.ParseInfoPage(new Uri(page, page.Segments.Last().RemoveTrailing("/") + ".info"));
            var imagesWithInfo = images
                .Apply(i => i.Add("Date", (DateTime)info["DATE"]))
                .Apply(i => i.Add("Note Title", (string)info["TITLE"]))
                .Apply(i => i.Add("Experiment", "ATLAS"))
                .Apply(i => i.Add("More Information", "Note Page", page));

            ///
            /// Add the ATLAS experiment catagory to this thing
            /// 

            return imagesWithInfo;
        }
    }
}
